package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.util.*;


/** 待定参数
 * name：学号
 * password：密码
 * kch_id；想抢的课程id
 * kcmc: 课程名称 由（kch_id）kcmc - 2.0 学分组成（有空格）
 */

public class TestLogin {

    public static void main(String[] args)throws Exception {
        TestLogin testLogin = new TestLogin();
        testLogin.beginLogin();
//        testLogin.getStudentGrade(2020,1);
        testLogin.getCourse();
    }

    //自输入
    private String name = "2018044743***";
    private String password = "123456";
    private String kch_id="203991200";
    private String kcmc = "(203991200)Photoshop 数字图像处理 - 2.0 学分"; //课程名称  (kch_id)kcmc - 2.0 学分
    //132 184 133 135 136 输入可流畅的IP地址，自测
    private String URL = "http://10.0.10.132/jwglxt";


    private Connection connection;
    private Response response,response2;
    private Document document;
    private List<Element> elements;
    private Map<String, String> datas;
    private Map<String,String> cookies_innet;
    private Map<String,String> cookies;
    private String csrftoken;
    private Map<String,String> cookies_3;

    //course参数
    private String jg_id="201";//学院
    private String zyh_id="0409";//专业号
    private String zyfx_id;
    private String njdm_id;
    private String bh_id;
    private String ccdm;
    private String xbm;


    //course2参数
    private String do_jxb_id;
    private String xkkz_id;


    //登录
    public boolean beginLogin() throws Exception{

        //第一次模拟登录获取cookies等信息
        connection = Jsoup.connect(URL+"/xtgl/login_slogin.html");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        connection.header("Content-Type","application/x-www-form-urlencoded");
        response = connection.execute();
        document = Jsoup.parse(response.body());
        elements = document.select("form");
        datas = new HashMap<>();
        for (Element e : elements.get(0).getAllElements()) {
            if (e.attr("name").equals("yhm")) {
                e.attr("value", name);
            }
            if (e.attr("name").equals("mm")) {
                e.attr("value", password);
            }
            if (e.attr("name").length() > 0) {
                datas.put(e.attr("name"), e.attr("value"));
            }
        }

        getCsrftoken();
        getRSApublickey();
//        System.out.println(cookies_innet);
        //第二次登录
        Connection connection2 = Jsoup.connect(URL+"/xtgl/login_slogin.html").cookies(cookies_innet);
        connection2.header("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        connection2.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器

        connection2.data("csrftoken",csrftoken);
        connection2.data("yhm",name);
        connection2.data("mm",password);
        connection2.data("mm",password);
        connection2.cookies(cookies).ignoreContentType(true)
                .method(Connection.Method.POST).execute();

        cookies_3=connection2.request().cookies();
        cookies_3.remove("rememberMe");

        response = connection2.followRedirects(true).execute();
        document = Jsoup.parse(response.body());

//        System.out.println(cookies_3);
        //登录成功
//        System.out.println(document);
        if(document.getElementById("tips") == null){
            System.out.println("欢迎登录");
            System.out.println(cookies_3);
            return true;
        }else{
            System.out.println(document.getElementById("tips").text());
            System.out.println(response.cookies());
            return false;
        }
    }

    // 获取csrftoken和Cookies
    private void getCsrftoken(){
        try{
            cookies_innet = response.cookies();
            Connection connection = Jsoup.connect(URL+ "/xtgl/login_slogin.html?time"+new Date().getTime()).cookies(cookies_innet);
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
            response = connection.followRedirects(true).method(Connection.Method.POST).execute();
            cookies = response.cookies();
            //保存csrftoken
            document = Jsoup.parse(response.body());
            csrftoken = document.getElementById("csrftoken").val();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    // 获取公钥并加密密码
    public void getRSApublickey() throws Exception{
        connection = Jsoup.connect(URL+"/xtgl/login_getPublicKey.html?time="+ new Date().getTime()).cookies(cookies_innet);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies).ignoreContentType(true).followRedirects(true).execute();

        JSONObject jsonObject = JSON.parseObject(response.body());
        String modulus = jsonObject.getString("modulus");
        String exponent = jsonObject.getString("exponent");
        password = RSAEncoder.RSAEncrypt(password, B64.b64tohex(modulus), B64.b64tohex(exponent));
        password = B64.hex2b64(password);
    }

    // 获取成绩信息
    public void getStudentGrade(int year , int term) throws Exception {
        Map<String,String> datas = new HashMap<>();
        datas.put("xnm",String.valueOf(year));
        datas.put("xqm",String.valueOf(term*term*3));
        datas.put("_search","false");
        datas.put("nd",String.valueOf(new Date().getTime()));
        datas.put("queryModel.showCount","15");
        datas.put("queryModel.currentPage","1");
        datas.put("queryModel.sortName","");
        datas.put("queryModel.sortOrder","asc");
        datas.put("queryModel.sortName","");
        datas.put("time","1");

        System.out.println(datas);

        //查询成绩
        connection = Jsoup.connect(URL+"/cjcx/cjcx_cxDgXscj.html?gnmkdm=N305005&layout=default&su=" + name);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies_innet).method(Connection.Method.POST).data(datas).ignoreContentType(true).execute();
        connection.cookies(cookies_3).method(Connection.Method.POST).ignoreContentType(true).execute();
        response = connection.followRedirects(true).execute();
        //选择查询
        connection = Jsoup.connect(URL+"/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=" + name);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies_3).method(Connection.Method.POST).data(datas).ignoreContentType(true).execute();
//        System.out.println(response);
        System.out.println(response.body());
        JSONObject jsonObject = JSON.parseObject(response.body());
        //System.out.println(jsonObject);
        JSONArray gradeTable = JSON.parseArray(jsonObject.getString("items"));
        //System.out.println(gradeTable);
        for (Iterator iterator = gradeTable.iterator(); iterator.hasNext();) {
            JSONObject lesson = (JSONObject) iterator.next();
            System.out.println("成绩成绩成绩成绩成绩成绩成绩成绩成绩成绩成绩成绩");
            System.out.println(lesson.getString("kcmc") + " " +
                    lesson.getString("jsxm") + " " +
                    lesson.getString("bfzcj") + " " +
                    lesson.getString("jd"));
        }
    }

    //抢课
    public void getCourse() throws Exception {

        //获取course参数
        connection = Jsoup.connect(URL+"/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default&su=" + name);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies_3).method(Connection.Method.POST).ignoreContentType(true).execute();
        jg_id = connection.get().getElementById("jg_id_1").val();
        zyh_id = connection.get().getElementById("zyh_id").val();
        zyfx_id = connection.get().getElementById("zyfx_id").val();
        njdm_id = connection.get().getElementById("njdm_id").val();
        bh_id = connection.get().getElementById("bh_id").val();
        ccdm = connection.get().getElementById("ccdm").val();
        xbm = connection.get().getElementById("xbm").val();
        System.out.println((jg_id)+" "+
                (zyh_id)+" "+
                (zyfx_id)+" "+
                (njdm_id)+" "+
                (bh_id)+" "+
                (ccdm)+" "+
                (xbm));


        Map<String,String> course = new HashMap<>();
        course.put("yl_list[0]","1"); //有无余量,注释该行课获取全部课表
        course.put("rwlx","2");
        course.put("xkly","0");
        course.put("bklx_id","0");
        course.put("xqh_id","1");
        course.put("jg_id",jg_id); //学院
        course.put("zyh_id",zyh_id); //专业号
        course.put("zyfx_id",zyfx_id);
        course.put("njdm_id",njdm_id);
        course.put("bh_id",bh_id);
        course.put("xbm",xbm);
        course.put("xslbdm","wlb");
        course.put("ccdm",ccdm);
        course.put("xsbj","4294967296");
        course.put("sfkknj","0");
        course.put("sfkkzy","0");
        course.put("sfznkx","0");
        course.put("zdkxms","0");
        course.put("sfkxq","0");
        course.put("sfkcfx","0");
        course.put("kkbk","0");
        course.put("kkbkdj","0");
        course.put("sfkgbcx","0");
        course.put("sfrxtgkcxd","0");
        course.put("tykczgxdcs","0");
        course.put("xkxnm","2020");
        course.put("xkxqm","12");
        course.put("kklxdm","10");
        course.put("rlkz","0");
        course.put("xkzgbj","0");
        course.put("kspage","0");
        course.put("jspage","50");
        course.put("jxbzb","");


        System.out.println(course);

        //自主选课，查询课表
        connection = Jsoup.connect(URL+"/xsxk/zzxkyzb_cxZzxkYzbPartDisplay.html?gnmkdm=N253512&su=" + name);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies_3).method(Connection.Method.POST).data(course).ignoreContentType(true).execute();
        connection.cookies(cookies_3).method(Connection.Method.POST).ignoreContentType(true).execute();
        response = connection.followRedirects(true).execute();
        System.out.println(response.body());
        JSONObject jsonObject = JSON.parseObject(response.body());
        //System.out.println(jsonObject);
        JSONArray gradeTable = JSON.parseArray(jsonObject.getString("tmpList"));
        //System.out.println(gradeTable);
        for (Iterator iterator = gradeTable.iterator(); iterator.hasNext();) {
            JSONObject lesson = (JSONObject) iterator.next();
            System.out.println(lesson.getString("jxb_id") + " " +
                    lesson.getString("jxbmc") + " " +
                    lesson.getString("kch_id") + " " +
                    lesson.getString("kcmc"));
        }

        //获取xkkz_id
        //firstXkkzId
        connection = Jsoup.connect(URL+"/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default&su=" + name);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies_3).method(Connection.Method.POST).data(course).ignoreContentType(true).execute();
        xkkz_id = connection.get().getElementById("firstXkkzId").val();
        System.out.println(xkkz_id);


        //根据所要抢的课程号获取对应的do_jxb_id
        Map<String,String> course2 = new HashMap<>();
        course2.put("rwlx","2");
        course2.put("xkly","0");
        course2.put("bklx_id","0");
        course2.put("xqh_id","1");
        course2.put("jg_id",jg_id); //学院
        course2.put("zyh_id",zyh_id); //专业号
        course2.put("zyfx_id",zyfx_id);
        course2.put("njdm_id",njdm_id);
        course2.put("bh_id",bh_id);
        course2.put("xbm",xbm);
        course2.put("xslbdm","wlb");
        course2.put("ccdm",ccdm);
        course2.put("xsbj","4294967296");
        course2.put("sfkknj","0");
        course2.put("sfkkzy","0");
        course2.put("sfznkx","0");
        course2.put("zdkxms","0");
        course2.put("sfkxq","0");
        course2.put("sfkcfx","0");
        course2.put("kkbk","0");
        course2.put("kkbkdj","0");
        course2.put("xkxnm","2020");
        course2.put("xkxqm","12");
        course2.put("rlkz","0");
        course2.put("kklxdm","10");
        course2.put("kch_id",kch_id);//课程号
        course2.put("xkkz_id",xkkz_id);
        course2.put("cxbj","0");
        course2.put("fxbj","0");

        System.out.println("===================================================================================");

        //获取do_jxb_id
        connection = Jsoup.connect(URL+"/xsxk/zzxkyzbjk_cxJxbWithKchZzxkYzb.html?gnmkdm=N253512&su=" + name);
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
        response = connection.cookies(cookies_3).method(Connection.Method.POST).data(course2).ignoreContentType(true).execute();
        connection.cookies(cookies_3).method(Connection.Method.POST).ignoreContentType(true).execute();
        response = connection.followRedirects(true).execute();
//        System.out.println(response.body());
        JSONArray gradeTable1 = JSON.parseArray(response.body());
//        System.out.println(gradeTable1);
        //输出课程老师信息
        for (Iterator iterator = gradeTable1.iterator(); iterator.hasNext();) {
            JSONObject lesson = (JSONObject) iterator.next();
            System.out.println(lesson.getString("kkxymc") + " " +
                    lesson.getString("jxb_id") + " " +
                    lesson.getString("kcgsmc") + " " +
                    lesson.getString("do_jxb_id")+ " " +
                    lesson.getString("jsxx"));
            do_jxb_id = lesson.getString("do_jxb_id");
        }
        System.out.println(do_jxb_id);

        Map<String,String> datas = new HashMap<>();
        datas.put("jxb_ids",do_jxb_id);
        datas.put("kch_id",kch_id);//课程号id
        datas.put("kcmc",kcmc);//课程名称  (kch_id)kcmc - 2.0 学分
        datas.put("rwlx","2");
        datas.put("rlkz","0");
        datas.put("rlzlkz","1");
        datas.put("sxbj","1");
        datas.put("xxkbj","0");
        datas.put("qz","0");
        datas.put("cxbj","0");
        datas.put("xkkz_id",xkkz_id);
        datas.put("njdm_id",njdm_id);
        datas.put("zyh_id",zyh_id);
        datas.put("kklxdm","10");
        datas.put("xklc","1");
        datas.put("xkxnm","2020");
        datas.put("xkxqm","12");


        //抢课,防止乱抢，建议获取余量课表前先注释
//        connection = Jsoup.connect(URL+"/xsxk/zzxkyzbjk_xkBcZyZzxkYzb.html?gnmkdm=N253512&su=" + name);
//        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36");//配置模拟浏览器
//        response = connection.cookies(cookies_3).method(Connection.Method.POST).data(datas).ignoreContentType(true).execute();
//        connection.cookies(cookies_3).method(Connection.Method.POST).ignoreContentType(true).execute();
//        response = connection.followRedirects(true).execute();
//        System.out.println(response);
    }

}
